package calorie.com.calorie.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ido.ble.BLEManager;
import com.ido.ble.LocalDataManager;
import com.ido.ble.bluetooth.device.BLEDevice;
import com.ido.ble.callback.ConnectCallBack;
import com.ido.ble.callback.ScanCallBack;
import com.ido.ble.callback.SyncCallBack;
import com.ido.ble.data.manage.database.HealthBloodPressed;
import com.ido.ble.data.manage.database.HealthBloodPressedItem;
import com.ido.ble.data.manage.database.HealthHeartRate;
import com.ido.ble.data.manage.database.HealthHeartRateItem;
import com.ido.ble.data.manage.database.HealthSleep;
import com.ido.ble.data.manage.database.HealthSleepItem;
import com.ido.ble.data.manage.database.HealthSport;
import com.ido.ble.data.manage.database.HealthSportItem;
import com.lxh.baselibray.base.XActivity;
import com.lxh.baselibray.util.SPUtils;
import com.lxh.baselibray.util.ToastUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import calorie.com.calorie.R;
import calorie.com.calorie.adapter.ScanAdapter;
import calorie.com.calorie.constant.Constant;
import calorie.com.calorie.contact.UpdateBLEInfoContact;
import calorie.com.calorie.response.ResultDTO;
import calorie.com.calorie.response.UserAssets;
import calorie.com.calorie.util.StaticValue;
import retrofit2.Response;


public class ScanDeviceActivity extends XActivity implements View.OnClickListener {


    private ListView lView;
    private Button btnScan;
    private ScanAdapter adapter;
    private Handler mHandler = new Handler();
    private ArrayList<BLEDevice> list = new ArrayList<BLEDevice>();
    private Context context;
    public static int num = -1;
    private ProgressDialog progressDialog;
    private int selectIndex = -1;
    private View already_bing;
    private TextView ble_info;
    private TextView click_unbind;
    private String address;
    private String name;

    protected void showProgressDialog(String title) {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setTitle(title);
        progressDialog.show();
    }


    private ScanCallBack.ICallBack scanCallBack = new ScanCallBack.ICallBack() {
        @Override
        public void onStart() {

        }

        @Override
        public void onFindDevice(BLEDevice device) {

            for (int w = 0; w < list.size(); w++) {
                BLEDevice ble = list.get(w);
                if (ble.mDeviceAddress.equals(device.mDeviceAddress)) {
                    return;
                }
            }
            list.add(device);
            Log.e("找到手环", device.mDeviceAddress);

            Collections.sort(list);
            adapter.notifyDataSetChanged();

        }

        @Override
        public void onScanFinished() {
            btnScan.setText("点击扫描");
            if (list.size() == 0) {
               // ToastUtils.showLongToast(context, "附近没有设备");
            }
        }
    };

    protected void closeProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    private ConnectCallBack.ICallBack connectCallBack = new ConnectCallBack.ICallBack() {

        @Override
        public void onConnectStart() {

        }

        @Override
        public void onConnecting() {

        }

        @Override
        public void onConnectSuccess() {
            closeProgressDialog();
            ToastUtils.showLongToast(context, "连接成功");
            //if (list.size() > 0 && selectIndex != -1) {
            //adapter.setSelectDevice(list.get(selectIndex));
            //}
            if(list.size()>0){
                already_bing.setVisibility(View.VISIBLE);
                click_unbind.setText("点击绑定");
                ble_info.setText("已经连接：" + list.get(selectIndex).mDeviceName + "：" + list.get(selectIndex).mDeviceAddress);
                name = list.get(selectIndex).mDeviceName;
                address = list.get(selectIndex).mDeviceAddress;

                BLEManager.unregisterScanCallBack(scanCallBack);
                btnScan.setText("点击扫描");
            }

        }

        @Override
        public void onConnectFailed() {
            closeProgressDialog();
            ToastUtils.showLongToast(context, "连接失败");
        }

        @Override
        public void onConnectBreak() {

        }

        @Override
        public void onInDfuMode(BLEDevice bleDevice) {
            setTitle(getString(R.string.connect_state_dfu));
            handleDfuState(bleDevice);
        }

        @Override
        public void onInitCompleted() {
        }

    };

    private void handleDfuState(final BLEDevice bleDevice) {
        new AlertDialog.Builder(this).setTitle("提示")
                .setMessage("设备处于升级模式，是否去升级？").setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent();
                // intent.setClass(ScanDeviceActivity.this, MainDfuActivity.class);
                // intent.putExtra("mac_address", bleDevice.mDeviceAddress);
                //  intent.putExtra("device_id", bleDevice.mDeviceId + "");
                // startActivity(intent);
            }
        }).create().show();
    }

    private void retry() {
        //  list.clear();
        // adapter.clear();

        BLEManager.stopScanDevices();
        BLEManager.startScanDevices();
    }


    private SyncCallBack.IHealthCallBack iHealthCallBack = new SyncCallBack.IHealthCallBack() {
        @Override
        public void onStart() {

        }

        @Override
        public void onProgress(int progress) {

        }

        @Override
        public void onStop() {

        }

        @Override
        public void onSuccess() {
            HealthSport healthSport = LocalDataManager.getHealthSportByDay(2018, 11, 30);
            String str = new Gson().toJson(healthSport);


        }

        @Override
        public void onFailed() {

        }

        @Override
        public void onGetSportData(HealthSport healthSport, List<HealthSportItem> items) {

        }

        @Override
        public void onGetSleepData(HealthSleep healthSleep, List<HealthSleepItem> items) {

        }

        @Override
        public void onGetHeartRateData(HealthHeartRate healthHeartRate, List<HealthHeartRateItem> items) {

        }

        @Override
        public void onGetBloodPressureData(HealthBloodPressed healthBloodPressed, List<HealthBloodPressedItem> items) {

        }
    };

    @Override
    protected void onResume() {
        super.onResume();

    }

    public void initView() {
        lView = findViewById(R.id.lv_device);
        btnScan = findViewById(R.id.btn_scan);
        already_bing = findViewById(R.id.already_bing);
        ble_info = findViewById(R.id.ble_info);
        already_bing.setOnClickListener(this);
        click_unbind = findViewById(R.id.click_unbind);
        click_unbind.setOnClickListener(this);
        btnScan.setOnClickListener(this);
        adapter = new ScanAdapter(this, list);
        lView.setAdapter(adapter);
        lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
                selectIndex = index;
                showProgressDialog("连接中...");
                BLEDevice device = list.get(index);
                BLEManager.connect(device);
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //  BLEManager.stopScanDevices();
        //   BLEManager.unregisterScanCallBack(scanCallBack);
        //  BLEManager.unregisterConnectCallBack(connectCallBack);
        //  BLEManager.unregisterBindCallBack(adapter.bindCallBack);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_scan:
                if (!btnScan.getText().toString().equals("扫描中...")) {
                    btnScan.setText("扫描中...");
                    //BLEManager.disConnect();

                    BLEManager.registerScanCallBack(scanCallBack);
                    retry();
                }
                break;
            case R.id.click_unbind:
                if (click_unbind.getText().toString().equals("点击绑定")) {
                    BLEManager.bind();
                    UpdateBLEInfoContact.UpdateBLEInfoPresent present = new UpdateBLEInfoContact.UpdateBLEInfoPresent();
                    int id = SPUtils.getInt(Constant.USER_ID, 0, context);
                    present.setiUpdateBELView(new UpdateBELView());
                    present.updateBLE(id, address, name);
                } else {
                    if (BLEManager.isConnected()) {
                        BLEManager.disConnect();
                    }
                    BLEManager.unbind();
                    UpdateBLEInfoContact.UpdateBLEInfoPresent present = new UpdateBLEInfoContact.UpdateBLEInfoPresent();
                    int id = SPUtils.getInt(Constant.USER_ID, 0, context);
                    present.setiUpdateBELView(new UpdateBELView());
                    address = null;
                    name = null;
                    present.updateBLE(id, address, name);
                }


                break;
            default:
                break;
        }
    }


    class UpdateBELView implements UpdateBLEInfoContact.IUpdateBELView {
        @Override
        public void setResultDTO(Response<ResultDTO> response) {
            if (response.body().getCode().equals("200")) {
                if (name != null && !name.equals("")) {
                    click_unbind.setText("点击解绑");
                    ble_info.setText("已经绑定：" + list.get(selectIndex).mDeviceName + "：" + list.get(selectIndex).mDeviceAddress);
                    ToastUtils.showLongToast(context, "绑定成功");
                    BLEManager.stopScanDevices();
                    list.clear();
                    adapter.notifyDataSetChanged();
                    btnScan.setVisibility(View.GONE);

                } else {

                    ToastUtils.showLongToast(context, "解绑成功");
                    btnScan.setVisibility(View.VISIBLE);
                    already_bing.setVisibility(View.GONE);
                }
                Gson gs = new Gson();
                StaticValue.userAssets = gs.fromJson(gs.toJson(response.body().getData()), UserAssets.class);//保存用户资产信息
                SPUtils.putString(Constant.BLEADDRESS, StaticValue.userAssets.getBleAddress(), context);
                SPUtils.putString(Constant.BLENAME, StaticValue.userAssets.getBleName(), context);//保存手环信息
            } else if(response.body().getCode().equals("201")){
                ToastUtils.showLongToast(context, "服务器异常");
            }else{
                ToastUtils.showLongToast(context, response.body().getMsg());
            }
        }
    }

    private void showList(final BLEDevice device) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                adapter.upDada(device);
            }
        });
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        int version = android.os.Build.VERSION.SDK_INT;
        if (version >= 23) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.REQUEST_INSTALL_PACKAGES, Manifest.permission.READ_EXTERNAL_STORAGE}, 127);
            if((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                    || (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)){
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION},127);
            }
        }



     //   requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 127);
        initView();
       // BLEManager.registerScanCallBack(scanCallBack);
        BLEManager.registerConnectCallBack(connectCallBack);
        BLEManager.registerBindCallBack(adapter.bindCallBack);
        BLEManager.registerUnbindCallBack(adapter.unbindCallBack);
        BLEManager.registerSyncHealthCallBack(iHealthCallBack);

        btnScan.setText("点击扫描");
        context = this;
        address = SPUtils.getString(Constant.BLEADDRESS, "", context);
        name = SPUtils.getString(Constant.BLENAME, "", context);
        if (!address.equals("") && !name.equals("")) {
            already_bing.setVisibility(View.VISIBLE);//已经绑定的清空下，直接显示已经绑定的手环的信息
            ble_info.setText("已绑定： " + name + ":" + address);
            btnScan.setVisibility(View.GONE);
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        BLEManager.unregisterScanCallBack(scanCallBack);
        BLEManager.unregisterConnectCallBack(connectCallBack);//连接
        BLEManager.unregisterBindCallBack(adapter.bindCallBack);//绑定
        BLEManager.unregisterSyncHealthCallBack(iHealthCallBack);//数据同步
        BLEManager.unregisterUnbindCallBack(adapter.unbindCallBack);//数据同步

    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_scan;
    }
}
